﻿using System.Net;
using System.Net.Sockets;
using MoonFramework.Net;
using MoonFramework.Tool;
using Proto;
using Serilog;

namespace TestClient
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            //初始化日志环境
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug() // debug
                .WriteTo.Console()
                .WriteTo.File("logs//client-log.txt", rollingInterval: RollingInterval.Day)
                .CreateLogger();
            //Test();
            IPEndPoint ipEndPoint = new(IPAddress.Parse("127.0.0.1"), 8086);
            Socket socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Console.ReadKey();
            await socket.ConnectAsync(ipEndPoint);
            BaseConnection connection = new();
            connection.DataReceived += DataReceived;
            connection.DisConnected += DisConnected;
            Log.Debug("服务器连接");
            connection.Start(socket: socket);
            for (int i = 0; i < 100000; i++)
            {
                Log.Debug("发送了一条消息");
                
            }

            Console.ReadKey();
        }

        private static void Test()
        {
            ulong l = 0, r = Int64.MaxValue;
            while (l < r)
            {
                ulong mid = (l + r) >> 1;
                if (DataSerializer.VariantSize(mid) >= BitConverter.GetBytes(mid).Length) r = mid;
                else l = mid + 1L;
            }
            Log.Debug("{0} {1}",DataSerializer.VariantSize(l), BitConverter.GetBytes(l).Length);
            Log.Debug("{0}", l);
        }

        //连接断开
        private static void DisConnected(BaseConnection obj)
        {
            //TODO:处理连接断开回调
            Log.Information("连接断开");
        }

        //接收消息
        private static void DataReceived(BaseConnection sender, byte[] bytes)
        {
            Package message = ProtoTool.Deserialize<Package>(bytes);
            MessageRouter.Instance.SendMessage(sender, message);
        }
    }
}